<?php

namespace app\admin\model;

use ShidianUtil\Utils\StringUtil;
use think\exception\ValidateException;
use think\facade\Request;

/**
 * Class ExternalPlatform
 * @package app\admin\model
 * @property string $name
 * @property string $platform
 * @property string $salt
 * @property string $token
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class ExternalPlatform extends \app\common\model\BaseModel
{

    protected $name = 'ExternalPlatform';

    /**
     * 获取UM模型
     * @param $id
     * @return \app\admin\model\ExternalPlatform|null
     */
    protected static function UM($token): ?ExternalPlatform
    {
        return ExternalPlatform::where('token', $token)->find();
    }

    /**
     * 依赖注入的时候获取当前UM模型
     * @return \app\admin\model\ExternalPlatform|null
     */
    public static function __make()
    {
        $token = Request::header('token', null);

        if (is_blank($token)) {
            return null;
        }
        $random = Request::header('random');
        $sign = Request::header('sign');

        $um = static::UM($token);

        if (is_null($um)) {
            throw new ValidateException('[token]错误');
        }

        $salt = $um->salt;

        $sign0 = md5($salt . $token . $random);

        if(!StringUtil::equals($sign0, $sign)){
            throw new ValidateException('验签错误');
        }

        return $um;
    }
    /**
     * 1对1
     * @return \think\model\relation\HasOne
     */
    //    public function one(){
    //        return $this->hasOne( Test1::class, 'Test1表中的键', 'User表中的键');
    //    }

    /**
     * 1对多
     * @return \think\model\relation\HasMany
     */
    //    public function many(){
    //        return $this->hasMany( Test1::class, 'Test1表中的键', 'User表中的键');
    //    }

    /**
     * 多对多
     * @return \think\model\relation\BelongsToMany
     */
    //    public function belongs(){
    //        return $this->belongsToMany( Test1::class, '中间表', '中间表中Test1的键', '中间表中User的键');
    //    }
}
